<template>
   
  <div>
    <el-upload
      action="http://mail-yhz.oss-cn-guangzhou.aliyuncs.com"
      :data="dataObj"
      :multiple="false"
      :file-list="fileList"
      :show-file-list="false"
      :before-upload="beforeUpload"
      :on-success="handleUploadSuccess"
      :auto-upload="true"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar" />
      <el-image v-else>
        <div slot="error" class="image-slot">
          <i class="el-icon-picture-outline error"></i>
        </div>
      </el-image>
      <div slot="tip" class="el-upload__tip">
        只能上传jpg/png文件，且不超过5MB
      </div>
    </el-upload>
  </div>
</template>
<script>
import { uploadImgs } from "./policy";
import { getUUID } from "@/utils";

export default {
  name: "singleUpload",
  props: {
    value: String,
  },
  computed: {
    imageUrl() {
      return this.value;
    },
    imageName() {
      if (this.value != null && this.value !== "") {
        return this.value.substr(this.value.lastIndexOf("/") + 1);
      } else {
        return null;
      }
    },
  },
  data() {
    return {
      dataObj: {
        policy: "",
        signature: "",
        key: "",
        ossaccessKeyId: "",
        dir: "",
        host: "",
        // callback:'',
      },
      fileList: [],
    };
  },
  created() {
    uploadImgs()
      .then((response) => {
        this.dataObj.policy = response.data.policy;
        this.dataObj.signature = response.data.signature;
        this.dataObj.ossaccessKeyId = response.data.accessid;
        this.dataObj.dir = response.data.dir;
        this.dataObj.host = response.data.host;
        resolve(true);
      })
      .catch((err) => {
        reject(false);
      });
  },
  methods: {
    emitInput(val) {
      this.$emit("modifyAvatar", val);
    },

    beforeUpload(file) {
      this.dataObj.key = this.dataObj.dir + getUUID() + "_" + "${filename}";
    },
    handleUploadSuccess(res, file) {
      if (this.fileList != null) {
        this.fileList.pop();
      }
      this.fileList.push({
        name: file.name,
        url:
          this.dataObj.host +
          "/" +
          this.dataObj.key.replace("${filename}", file.name),
      });
      this.emitInput(this.fileList[0].url);
    },
  },
};
</script>
<style scoped>
.avatar {
  width: 120px;
  height: 120px;
}

.error {
  width: 100px;
  height: 100%;
}
</style>


